const websocket = require("./websocket")
const db = require("./db")
const websocketOrder = require("./websocket_order")
const PS3838Client = require("./ps3838api")


const orderClient = new PS3838Client({
    username: 'BIA00030TP',
    password: 'wwss2233'
});


var HGA_LIST = {
    updateTime: 0,
    data: []
};
var PS_LIST = {
    updateTime: 0,
    data: []
}

var HGA_MAP = new Map();// key:比赛ID， value:红牌时比赛数据 用途：用来检测下单前数据是否变化
var MATCH_HISTORY = new Map();// 匹配历史
var RED_ENVENT = new Map();

var SAME_TIME_MARKET = new Map(); // 同时出现盘口

// 联赛黑名单
var LEAGUE_BLOCK = ["友谊赛", "澳大利亚"]

var defaultMoney = 50; // 默认下注金额
var defaultMoneyPS = 17; // 默认下注金额
// 获取HGA数据
exports.update_hga_data = async function (data) {
    // 根据新的数据和旧的数据进行比较，判断是否有红牌变化
    let diff = Date.now() - HGA_LIST.updateTime
    for (let i = 0; i < data.length; i++) {
        let hgaGame = data[i].match;
        let isBlack = false;
        for (let x = 0; x < LEAGUE_BLOCK.length; x++) {
            if (hgaGame.zh.league.indexOf(LEAGUE_BLOCK[x]) >= 0) {
                isBlack = true;
                break;
            }
        }
        if (isBlack) continue; // 黑名单联赛不处理
        for (let j = 0; j < HGA_LIST.data.length; j++) {
            let oldGame = HGA_LIST.data[j].match;
            if (hgaGame.id === oldGame.id) {
                if (parseInt(hgaGame.homeRed) > parseInt(oldGame.homeRed) || parseInt(hgaGame.awayRed) > parseInt(oldGame.awayRed)) {
                    // 判断红牌时间
                    let period = hgaGame.period
                    let periods = period.split("^")
                    if (periods[0] == "2H" || periods[0] == "1H") {
                        let tm = periods[1].split(":")[0] // 获取分钟数
                        // 如果分钟数小于等于65，并且有红牌数量为1
                        if (parseInt(tm) <= 65 && (hgaGame.homeRed == 1 || hgaGame.awayRed == 1)) {
                            global.PS_OPEN = true
                            RED_ENVENT.set(hgaGame.id, Date.now())
                            global.log(`${tm} - 新红牌变化: [${hgaGame.zh.home} v ${hgaGame.zh.away}]  ${oldGame.homeRed}-${oldGame.awayRed}  -->  ${hgaGame.homeRed}-${hgaGame.awayRed}`);
                            db.createRedHistory(hgaGame.id, `${hgaGame.zh.home} v ${hgaGame.zh.away}`, hgaGame.zh.league);
                            // 向网页客户端
                            websocket.send({
                                type: "titan007_red_card_change",
                                data: {
                                    matchId: hgaGame.id,
                                    team1: hgaGame.zh.home,
                                    team2: hgaGame.zh.away,
                                    redCardCount: `${hgaGame.homeRed}-${hgaGame.awayRed}`,
                                    redCardOld: `${oldGame.homeRed}-${oldGame.awayRed}`,
                                }
                            });
                        }
                    }
                }
            }
        }
    }
    console.info(`HGA更新: ${diff / 1000}秒 | 红牌数量：${RED_ENVENT.size} | PS状态：${global.PS_OPEN} | HG用户: ${global.AccountMap.size}`)
    exports.delete_red_event();
    HGA_LIST.data = data;
    HGA_LIST.updateTime = Date.now();
    if (global.PS_OPEN && PS_LIST.data.length > 0) {
        exports.match_game("hga")
    }
}

// 获取平博数据
exports.update_ps3838_data = async function (data) {
    PS_LIST = {
        updateTime: Date.now(),
        data: data
    }
    exports.match_game("ps3838")
    exports.delete_red_event();
}

// 检测红牌事件
exports.delete_red_event = function () {
    RED_ENVENT.forEach((value, key) => {
        console.log(`检测红牌有效期 :Key: ${key}, Value: ${value}`);
        if (Date.now() - value > 900000) {
            RED_ENVENT.delete(key)
        }
    });
    if (RED_ENVENT.size == 0) {
        global.PS_OPEN = false
    }
    if (!global.PS_OPEN) {
        PS_LIST = {
            updateTime: 0,
            data: []
        }
    }
}

const PM = 0.98625

var PAM_MAP = new Map(); // 平博崩水值映射 PAM_MAP 记录了：平博和皇冠同时出现盘口时 皇冠的盘口 崩水值 下单方向 记录的时间 
var BENGSHUI_LIST = [] // 崩水比赛ID
var ORDERED_LIST = [] // 已下单比赛ID

var TEST_PS = false; // 测试平博下单
// 匹配比赛
exports.match_game = function (updateSite) {
    let games = []
    if (PS_LIST.updateTime != 0 && Date.now() - PS_LIST.updateTime > 10000) {
        global.info(`[${updateSite}]平博数据超过6秒未更新，停止监控 ${PS_LIST.updateTime}`)
        return
    }
    if (HGA_LIST.updateTime != 0 && Date.now() - HGA_LIST.updateTime > 6000) {
        global.info(`皇冠数据超过6秒未更新，停止监控 ${HGA_LIST.updateTime}`)
        return
    }
    if (HGA_LIST.data.length > 0 && PS_LIST.data.length > 0) {
        for (let i = 0; i < HGA_LIST.data.length; i++) {
            let hgaGame = HGA_LIST.data[i].match;
            // 如果当前比赛的ID在MATCH_HISTORY中存在，说明是历史比赛
            let pstId = false
            if (MATCH_HISTORY.has(hgaGame.id)) {
                pstId = MATCH_HISTORY.get(hgaGame.id).psId; // 获取平博的ID
            }
            for (let j = 0; j < PS_LIST.data.length; j++) {
                let psGame = PS_LIST.data[j];
                let isMatch = false
                let id = Date.now();
                let game = {
                    id: id,
                    league: hgaGame.zh.league,
                    home: hgaGame.zh.home,
                    away: hgaGame.zh.away,
                    homeEn: hgaGame.en.home,
                    awayEn: hgaGame.en.away,
                    matchId: hgaGame.id,// 使用皇冠ID
                    psId: psGame.id, // 平博的ID
                    score: `${hgaGame.homeScore}-${hgaGame.awayScore}`,
                    redScore: `${hgaGame.homeRed}-${hgaGame.awayRed}`,
                    time: hgaGame.period,
                    market: {
                        hga: HGA_LIST.data[i].markets,
                        ps3838: { handap: psGame.handap, }
                    },
                    psMarketStatus: psGame.status,
                    ps_home: psGame.home,
                    ps_away: psGame.away,
                    updateTimeHG: HGA_LIST.updateTime,
                    updateTimePS: PS_LIST.updateTime,
                    updateSite: updateSite,
                    orderData: "",
                    psOrderData: "",
                }
                // 判断比分
                if (psGame.score == `${hgaGame.homeScore}:${hgaGame.awayScore}`) {
                    if (hgaGame.en.home === psGame.home) {
                        isMatch = true
                    }
                    if (hgaGame.en.away === psGame.away) {
                        isMatch = true
                    }
                    if (hgaGame.en.home.indexOf(psGame.home) >= 0 || hgaGame.en.away.indexOf(psGame.away) >= 0) {
                        isMatch = true
                    }
                    if (getName(hgaGame.en.home).indexOf(getName(psGame.home)) >= 0 || getName(hgaGame.en.away).indexOf(getName(psGame.away)) >= 0) {
                        isMatch = true
                    }
                    if (isMatch) {
                        games.push(game);
                        MATCH_HISTORY.set(game.matchId, game);

                        // if (!TEST_PS) {
                        //     let market = game.market
                        //     let psMarket = market.ps3838;
                        //     let psMap = new Map();
                        //     for (let j = 0; j < psMarket.handap.length; j++) {
                        //         let psMarketHdp = psMarket.handap[j]
                        //         if (psMarketHdp) {
                        //             psMap.set(psMarketHdp.v + "", {
                        //                 home: psMarketHdp.a,
                        //                 away: psMarketHdp.b,
                        //                 altLineId: psMarketHdp.altLineId,
                        //                 lineId: psMarketHdp.lineId,
                        //                 eventId: psMarketHdp.eventId,
                        //                 periodNumber: psMarketHdp.periodNumber,
                        //                 handap: psMarketHdp.v + "",
                        //             });
                        //         }
                        //     }
                        //     let isOrder = false;
                        //     psMap.forEach((maxPAM, k) => {
                        //         global.info(`测试平博盘口: 主赔：${maxPAM.home} 客赔：${maxPAM.away} 盘口: ${maxPAM.handap} `);
                        //         try {
                        //             let psOrderData = {}
                        //             psOrderData.stake = defaultMoneyPS;
                        //             psOrderData.eventId = game.psId;
                        //             psOrderData.lineId = maxPAM.lineId;
                        //             psOrderData.altLineId = maxPAM.altLineId;
                        //             psOrderData.periodNumber = maxPAM.periodNumber;
                        //             psOrderData.sportId = 29;
                        //             psOrderData.betType = "SPREAD";
                        //             psOrderData.handicap = maxPAM.handap;
                        //             psOrderData.team = "TEAM1";
                        //             psOrderData.side = null;
                        //             psOrderData.handicap = maxPAM.handap;
                        //             game.psOrderData = JSON.stringify(psOrderData);
                        //             global.info(`开始下单平博: ${JSON.stringify(psOrderData)}`);
                        //             global.info(`开始下单平博: 2`);
                        //             if (!isOrder) {
                        //                 isOrder = true;
                        //                 TEST_PS = true;
                        //                 orderClient.placeBet(psOrderData)
                        //             }
                        //         } catch (e) {
                        //             global.info(`下单平博异常: ${e.message}`) // 捕获错误信息
                        //         }
                        //     })

                        // }









                        // 红牌 且 未下单
                        if (RED_ENVENT.has(game.matchId) && !ORDERED_LIST.includes(game.matchId)) {
                            let t = RED_ENVENT.get(game.matchId)
                            // 红牌发生时间 小于15分钟 
                            if (Date.now() - t < 900000) {
                                global.PS_OPEN = true
                                let market = game.market
                                let hgaMarket = market.hga;
                                let psMarket = market.ps3838;
                                // --------------------- 第一步：解析映射最新盘口赔率数据 -----------------------
                                // 最新数据： 映射皇冠盘口和赔率
                                let hgaMap = new Map();
                                // 最新数据：映射平博盘口和赔率
                                let psMap = new Map();
                                for (let j = 0; j < hgaMarket.length; j++) {
                                    let hgaMarketHdp = hgaMarket[j]
                                    if (hgaMarketHdp.type == "滚球让球") {
                                        if (hgaMarketHdp) {
                                            hgaMap.set(hgaMarketHdp.handicap + "", {
                                                id: hgaMarketHdp.id,
                                                home: hgaMarketHdp.homeOdds,
                                                away: hgaMarketHdp.awayOdds
                                            });
                                        }
                                    }
                                }
                                for (let j = 0; j < psMarket.handap.length; j++) {
                                    let psMarketHdp = psMarket.handap[j]
                                    if (psMarketHdp) {
                                        psMap.set(psMarketHdp.v + "", {
                                            home: psMarketHdp.a,
                                            away: psMarketHdp.b,
                                            altLineId: psMarketHdp.altLineId,
                                            lineId: psMarketHdp.lineId,
                                            eventId: game.psId,
                                            periodNumber: psMarketHdp.periodNumber,
                                            handap: psMarketHdp.v + "",
                                        });
                                    }
                                }
                                // global.info(`第一步：监控中: [${game.home} v ${game.away}]  皇冠盘口数量: ${hgaMap.size}  平博盘口数量: ${psMap.size}`);
                                // --------------------- 第二步：判断盘口是否同时存在 -----------------------
                                // 皇冠和平博盘口都存在   
                                if (hgaMap.size > 0 && psMap.size > 0) {
                                    let PS_PREORDER = new Map(); // 记录准备下单的平博盘口
                                    // 判断是否是第一次出现盘口
                                    if (!SAME_TIME_MARKET.has(game.matchId)) {
                                        // 第一次出现盘口
                                        global.log(`第二步：同一时间盘口出现: [${game.home} v ${game.away}]  ${game.score}  ${game.time}  ${game.ps_home} v ${game.ps_away}`);
                                        // 记录平博
                                        hgaMap.forEach((hgm, key) => {
                                            let psm = psMap.get(key) // 获取平博盘口 
                                            global.info(`当前盘口[${key}] 对比盘口赔率数据: 平博盘口:${[...psMap.keys()].map(String)}  皇冠盘口:${[...hgaMap.keys()].map(String)}`)
                                            if (psm) {
                                                global.log(`第二步：盘口: ${key}  皇冠: ${hgm.home} - ${hgm.away} 平博：${psm.home} - ${psm.away}   `);
                                                // 计算P值
                                                let p1 = 1 / (1 / (parseFloat(psm.away) + 1) + 1 / (parseFloat(hgm.home) + 1));// 平博客 皇冠主 
                                                let p2 = 1 / (1 / (parseFloat(psm.home) + 1) + 1 / (parseFloat(hgm.away) + 1));// 平博主 皇冠客  
                                                let target = "";
                                                let PAM = 0;
                                                if (p1 >= 1 && p1 < 1.2) {
                                                    if (psm.away >= 0.7 && psm.away < 2) {
                                                        PS_PREORDER.set(key, {
                                                            target: "平博客",
                                                            market: psm,
                                                        });
                                                    }
                                                    // 平博客
                                                    PAM = 1 / (1 / PM - 1 / (parseFloat(hgm.home) + 1)) //  平博崩水值 
                                                    target = "平博客"
                                                    global.log(`第二步：确定方向 盘口: ${key} 平博客 P值: ${p1} PAM: ${PAM}`);

                                                }
                                                if (p2 >= 1 && p2 < 1.2) {
                                                    if (psm.home >= 0.7 && psm.home < 2) {
                                                        PS_PREORDER.set(key, {
                                                            target: "平博主",
                                                            market: psm,
                                                        });
                                                    }
                                                    // 平博主
                                                    PAM = 1 / (1 / PM - 1 / (parseFloat(hgm.away) + 1)) //  平博崩水值 
                                                    target = "平博主"
                                                    global.log(`第二步：确定方向 盘口: ${key} 平博主 P值:  ${p2} PAM: ${PAM}`);
                                                }
                                                if (PAM < 2) {
                                                    // 取PAM的3为小数四舍五入 
                                                    PAM = Number(PAM.toFixed(3))
                                                } else {
                                                    // 取PAM的2为小数 四舍五入
                                                    PAM = Number(PAM.toFixed(2))
                                                }
                                                if (target != "") {
                                                    if (PAM_MAP.has(game.matchId)) {
                                                        let pams = PAM_MAP.get(game.matchId);
                                                        pams.push({
                                                            gameId: id,// 因为会定时记录比赛所有数据，所以这里的gameId指的是某一次更新的比赛数据id , 对应games表里面的id
                                                            NAB: key,
                                                            PAM: PAM,
                                                            mid: hgm.id,
                                                            target: target,
                                                            time: Date.now(),
                                                        })
                                                        PAM_MAP.set(game.matchId, pams);
                                                        HGA_MAP.set(game.id, game);
                                                    } else {
                                                        PAM_MAP.set(game.matchId, [{
                                                            gameId: id,
                                                            NAB: key,
                                                            PAM: PAM,
                                                            mid: hgm.id,
                                                            target: target,
                                                            time: Date.now(),
                                                        }]);
                                                        HGA_MAP.set(game.id, game);
                                                    }
                                                }
                                                global.log(`第二步：盘口: ${key} P值: ${p1} - ${p2}  PAM: ${PAM} target: ${target}`);
                                                SAME_TIME_MARKET.set(game.matchId, true);
                                            }
                                        });
                                    }
                                    // 判断是否满足平博下单
                                    if (PS_PREORDER.size > 0) {
                                        global.info(`第二步[平博]：检测平博盘口: ${[...PS_PREORDER.keys()].map(String)}`);
                                        // 判断PS_PREORDER中赔率最大的盘口进行下单
                                        let maxPAM = false;
                                        let pamTarget = "";
                                        PS_PREORDER.forEach((v, k) => {
                                            let psm = v.market;
                                            let target = v.target;
                                            if (target == "平博主") {
                                                if (maxPAM) {
                                                    if (psm.home > maxPAM.home) {
                                                        maxPAM = psm;
                                                    }
                                                } else {
                                                    maxPAM = psm;
                                                }
                                                pamTarget = target;
                                            }
                                            if (target == "平博客") {
                                                if (maxPAM) {
                                                    if (psm.away > maxPAM.away) {
                                                        maxPAM = psm;
                                                    }
                                                } else {
                                                    maxPAM = psm;
                                                }
                                                pamTarget = target;
                                            }
                                        })
                                        if (maxPAM) {
                                            global.info(`第二步[平博]：准备下单平博盘口: 主赔：${maxPAM.home} 客赔：${maxPAM.away} 盘口: ${maxPAM.handap} `);
                                            // 判断是否下单平博
                                            // 开始组装下单平博的参数
                                            global.info(`开始下单平博: 1`);
                                            try {
                                                let psOrderData = {}
                                                psOrderData.stake = defaultMoneyPS;
                                                psOrderData.eventId = game.psId;
                                                psOrderData.lineId = maxPAM.lineId;
                                                psOrderData.altLineId = maxPAM.altLineId;
                                                psOrderData.periodNumber = maxPAM.periodNumber;
                                                psOrderData.sportId = 29;
                                                psOrderData.betType = "SPREAD";
                                                psOrderData.handicap = maxPAM.handap;
                                                psOrderData.team = (pamTarget == "平博主") ? "TEAM1" : "TEAM2";
                                                psOrderData.side = null;
                                                psOrderData.handicap = maxPAM.handap;
                                                game.psOrderData = JSON.stringify(psOrderData);
                                                global.info(`开始下单平博: ${JSON.stringify(psOrderData)}`);
                                                global.info(`开始下单平博: 2`);
                                                orderClient.placeBet(psOrderData)
                                            } catch (e) {
                                                global.info(`下单平博异常: ${e.message}`) // 捕获错误信息
                                            }
                                        }
                                    }
                                }
                                // --------------------- 第三步：监控平博是否崩水 -----------------------
                                // 监控平博赔率是否崩水
                                // 不管皇冠是否存在盘口，都监控平博是否崩水 
                                if (PAM_MAP.has(game.matchId) && !BENGSHUI_LIST.includes(game.matchId)) {
                                    let pams = PAM_MAP.get(game.matchId);
                                    for (let k = 0; k < pams.length; k++) {
                                        let pam = pams[k];
                                        let psm = psMap.get(pam.NAB) // 获取平博盘口 
                                        if (!psm) continue; // 如果没有找到对应的盘口，就跳过
                                        // 当前时间 在 同时出现盘口的时间 一分钟之内
                                        if (pam.time + 60 * 1000 >= Date.now()) {
                                            // 获取当前平博盘口最新赔率数据
                                            // psMap 映射了 当前平博最新的盘口对应的赔率
                                            // 根据 PAM_MAP 记录的盘口（皇冠的盘口）获取平博盘口  
                                            global.info(`第三步：1分钟内监控：主赔：${psm.home} 客赔：${psm.away} 盘口: ${pam.NAB}  PAM: ${pam.PAM} target: ${pam.target}`);
                                            // 下单方向为平博主
                                            if (pam.target == "平博主") {
                                                // 当前平博主的赔率小于PAM 就意味着崩水
                                                if (parseFloat(psm.home) + 1 < pam.PAM) {
                                                    global.log(`平博主崩水: [${game.home} v ${game.away}]  ${game.score}  ${game.time}  最新赔率：主 ${psm.home} 盘口: ${pam.NAB}  PAM: ${pam.PAM} target: ${pam.target}`);
                                                    BENGSHUI_LIST.push(game.matchId)
                                                    break; // 只要有一个崩水就不再继续检查
                                                }
                                            }
                                            if (pam.target == "平博客") {
                                                if (parseFloat(psm.away) + 1 < pam.PAM) {
                                                    global.log(`平博客崩水: [${game.home} v ${game.away}]  ${game.score}  ${game.time}  最新赔率：客 ${psm.away}  盘口: ${pam.NAB}  PAM: ${pam.PAM} target: ${pam.target}`);
                                                    BENGSHUI_LIST.push(game.matchId)
                                                    break; // 只要有一个崩水就不再继续检查
                                                }
                                            }
                                        }
                                    }

                                }

                                // --------------------- 第四步：检测下单 -----------------------------
                                // 监控平博崩水的比赛
                                // 如果满足条件则下单皇冠
                                let orderData = false;
                                if (BENGSHUI_LIST.includes(game.matchId) && PAM_MAP.has(game.matchId) && HGA_MAP.has(game.matchId)) {
                                    let hgaGameTemp = HGA_MAP.get(game.matchId)
                                    if (game.score != hgaGameTemp.score || game.redScore != hgaGameTemp.redScore) {
                                        global.info(`第四步：比赛数据发生变化，终止下单。原始数据：比分[${score}] 红牌[${redScore}] 最新数据:比分[${game.score}] 红牌[${game.redScore}]`)
                                    } else {
                                        let pams = PAM_MAP.get(game.matchId);
                                        orderData = checkOrder(pams, psMap, hgaMap, game, orderData, 0.8);
                                        if (!orderData) {
                                            orderData = checkOrder(pams, psMap, hgaMap, game, orderData, 0.7);
                                        }
                                    }
                                }
                                if (orderData) {
                                    ORDERED_LIST.push(game.matchId)
                                    global.log(`下单成功。删除记录|已下单:[${game.matchId}] [${game.home} v ${game.away}] `);
                                    let dgir = PAM_MAP.delete(game.matchId); // 如果已经下单了，就删除这个盘口的记录 
                                    if (dgir) {
                                        global.log(`删除记录|已下单: 删除PAM_MAP记录成功`);
                                    }
                                }
                                //记录 下单信息 
                                game.orderData = orderData ? JSON.stringify(orderData) : "";
                            }
                            db.save(game)
                        }
                        break;
                    }


                }
            }
        }
    }
    if (games.length > 0) {
        websocket.send({
            type: "full_data",
            data: games
        })
    }
}


exports.get_red_event = function () {
    return RED_ENVENT;
}

function getName(name) {
    let originalName = name;
    if (name.length <= 3) return name;
    name = name.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
    // 1. 去除括号及其中的内容
    name = name.replace(/\s*\(.*?\)\s*/g, "").trim();

    // 2. 去除尾部数字
    name = name.replace(/\s+\d+$/g, "").trim();

    // 3. 后缀库（全量版）
    const suffixes = [
        "FC", "AFC", "SC", "SCC", "UNITED", "CITY", "ATHLETIC", "CLUB",
        "ROVERS", "RANGERS", "WANDERERS", "HOTSPUR", "ALBION",
        "CF", "CD", "SD", "UD", "S\\.D\\.", "AC", "US", "USC", "BK", "IK", "IL", "SK", "IF",
        "FK", "SV", "IFK", "OFK", "AGF", "MSV", "SE", "KRC", "PSV", "RFC", "OSC",
        "W", "WOMEN", "WOMAN", "F", "LADIES", "FEMENINO", "FEM", "DAMEN",
        "U17", "U18", "U19", "U20", "U21", "U23", "JUNIOR", "JUNIORS", "YOUTH",
        "RESERVE", "RESERVES", "B", "B-TEAM", "II"
    ];
    const regex = new RegExp(`\\s*\\b(?:${suffixes.join("|")})\\b\\.?$`, "i");
    // 4. 反复去除多个后缀
    while (regex.test(name)) {
        name = name.replace(regex, "").trim();
    }
    if (name.length <= 3) return originalName;
    return name;
}

// 下单检测
function checkOrder(pams, psMap, hgaMap, game, orderData, odds) {
    for (let k = 0; k < pams.length; k++) {
        let pam = pams[k];
        // let psm = psMap.get(pam.NAB); // 获取平博盘口
        let hgm = hgaMap.get(pam.NAB); // 获取皇冠盘口 
        let now = Date.now();
        // 2分钟之内
        if (now - pam.time <= 1000 * 60 * 2 && now - pam.time >= 1000 * 60) {
            global.info(`第四步[${odds}]：2分钟内监控：主赔：${hgm.home} 客赔：${hgm.away} 盘口: ${pam.NAB}  PAM: ${pam.PAM} target: ${pam.target}`);
            // 下单方向为平博主
            if (pam.target == "平博主") {
                if (parseFloat(hgm.home) < odds || parseFloat(hgm.home) > 2) {
                    global.log(`皇冠主下单: [${game.home} v ${game.away}]  皇冠主赔率不满足条件盘口[${pam.NAB}] ${hgm.home} - ${odds}  , 放弃下单`);
                    continue;
                }
                // 开始组装下单皇冠的参数
                let data = {
                    action: "order",
                    result: {
                        amount: defaultMoney,
                        gid: pam.mid,
                        wtype: "RE",
                        chose_team: "H"
                    }
                };
                orderData = {
                    "target": "皇冠主",
                    "home_odds": hgm.home,
                    "away_odds": hgm.away,
                    "handicap": pam.NAB,
                    "amount": defaultMoney,
                    "pam": pam.PAM,
                    "site": "hga"
                };
                // 在 pam.time 之后延迟1分钟下单
                // 这样可以避免平博赔率刚崩完就下单  
                websocketOrder.send(data);
                break;
            }
            if (pam.target == "平博客") {
                if (parseFloat(hgm.away) < odds || parseFloat(hgm.home) > 2) {
                    global.log(`皇冠客下单: [${game.home} v ${game.away}]  皇冠客赔率不满足条件[${pam.NAB}]  ${hgm.away} - ${odds} , 放弃下单`);
                    continue;
                }
                // 开始组装下单皇冠的参数
                let data = {
                    action: "order",
                    result: {
                        amount: defaultMoney,
                        gid: pam.mid,
                        wtype: "RE",
                        chose_team: "C"
                    }
                };
                orderData = {
                    "target": "皇冠客",
                    "home_odds": hgm.home,
                    "away_odds": hgm.away,
                    "handicap": pam.NAB,
                    "amount": defaultMoney,
                    "pam": pam.PAM,
                    "site": "hga"
                };
                websocketOrder.send(data);
                break;
            }
        }
    }
    return orderData;
}